import requests
import json
from time import sleep

def fsxx(input_strs,headers):
    url = 'https://m.weibo.cn/api/chat/send?content='+input_strs+'&uid=5175429989&_spr=screen%3A1368x912'
    page = requests.post(url, headers=headers)
    return page.json()['ok'] 

def sdxx(headers):
    xxlst = []
    url = 'https://m.weibo.cn/api/chat/list?count=10&uid=5175429989&unfollowing=0'
    response = requests.get(url , headers=headers)
    response.encoding="utf-8"
    for i in range(5):
        if response.json()["data"]["msgs"][i]['sender_id']==5175429989:
            text = response.json()["data"]["msgs"][i]["text"]
            xxlst.append(text)
    cookie = requests.utils.dict_from_cookiejar(response.cookies)
    return xxlst,cookie['XSRF-TOKEN']
#textheader 通过访问https://m.weibo.cn/message/chat?uid=5175429989&name=msgbox 并登录自己微博账号之后，复制请求标头的内容粘贴进来，开头为：的可以不复制。
#内容大概如下：
textheader = '''accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
content-length: 99
content-type: application/x-www-form-urlencoded
cookie: 
origin: https://m.weibo.cn
referer: https://m.weibo.cn/message/chat?uid=5175429989&name=msgbox
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 Edg/81.0.416.72
x-requested-with: XMLHttpRequest
x-xsrf-token: '''

lst = textheader.split("\n")
headers = {}
for i in lst:
    lslst = i.split(": ")
    if lslst[0] in ['accept','accept-encoding','accept-language','cookie','mweibo-pwa','origin','referer','sec-fetch-dest','sec-fetch-mode','sec-fetch-site','user-agent','x-requested-with','x-xsrf-token']:
        headers[lslst[0]]=lslst[1]

print('请使用"退出","quit","结束","exit"退出聊天')
xx,token = sdxx(headers)
lsxx = xx[0]
print("上次聊天【小冰】最后说：{}".format(lsxx))
headers['x-xsrf-token']=token

while True:
    txt = input()
    if txt in ["退出","quit","结束","exit"]:
        break
    elif txt == "":
        continue
    else:
        if fsxx(txt,headers) ==1:
            while True:
                sleep(3)
                xx,token = sdxx(headers)

                num = xx.index(lsxx)
                xxlst1 = xx[0:num]

                for j in range(len(xxlst1)):
                    msg = xxlst1.pop()
                    print("小冰说：{}".format(msg))
                    lsxx = msg

                headers['x-xsrf-token']=token
                if num > 0 and len(xxlst1)<2:
                    break
        else:
            print("【没有发送出去！】")
            xx,token = sdxx(headers)
            print("小冰之前说：{}".format(xx))
            headers['x-xsrf-token']=token